#!/bin/bash
#
# The 'run' performs a simple test that verifies that S2I image.
# The main focus here is to exercise the S2I scripts.
#
# IMAGE_NAME specifies a name of the candidate image used for testing.
# The image has to be available before this script is executed.
#
IMAGE_NAME=${IMAGE_NAME-centos/perl-520-centos-candidate}

# TODO: Make command compatible for Mac users
test_dir="$(readlink -zf $(dirname "${BASH_SOURCE[0]}"))"
image_dir=$(readlink -zf ${test_dir}/..)

source "${test_dir}/test-lib.sh"

# TODO: This should be part of the image metadata
test_port=8080

info() {
  echo -e "\n\e[1m[INFO] $@...\e[0m\n"
}

image_exists() {
  docker inspect $1 &>/dev/null
}

container_exists() {
  image_exists $(cat $cid_file)
}

container_ip() {
  docker inspect --format="{{ .NetworkSettings.IPAddress }}" $(cat $cid_file)
}

run_s2i_build() {
  s2i build "$@" file://${test_dir}/${test_name} ${IMAGE_NAME} ${IMAGE_NAME}-testapp
}

prepare() {
  if ! image_exists ${IMAGE_NAME}; then
    echo "ERROR: The image ${IMAGE_NAME} must exist before this script is executed."
    exit 1
  fi
  # TODO: S2I build require the application is a valid 'GIT' repository, we
  # should remove this restriction in the future when a file:// is used.
  info "Build the test application image"
  pushd ${test_dir}/${test_name} >/dev/null
  git init
  git config user.email "build@localhost" && git config user.name "builder"
  git add -A && git commit -m "Sample commit"
  popd >/dev/null
}

run_test_application() {
  docker run --user=100001 --rm --cidfile=${cid_file} ${IMAGE_NAME}-testapp
}

cleanup_test_app() {
  info "Cleaning up the test application"
  if [ -f $cid_file ]; then
    if container_exists; then
      docker stop $(cat $cid_file)
      docker rm $(cat $cid_file)
    fi
    rm $cid_file
  fi
}

cleanup() {
  info "Cleaning up the test application image"
  if image_exists ${IMAGE_NAME}-testapp; then
    docker rmi -f ${IMAGE_NAME}-testapp
  fi
  rm -rf ${test_dir}/${test_name}/.git
}

check_result() {
  local result="$1"
  if [[ "$result" != "0" ]]; then
    info "TEST FAILED (${result})"
    cleanup
    exit $result
  fi
}

wait_for_cid() {
  local max_attempts=10
  local sleep_time=1
  local attempt=1
  local result=1
  info "Waiting for application container to start"
  while [ $attempt -le $max_attempts ]; do
    [ -f $cid_file ] && [ -s $cid_file ] && break
    attempt=$(( $attempt + 1 ))
    sleep $sleep_time
  done
}

test_s2i_usage() {
  info "Testing 's2i usage'"
  s2i usage ${s2i_args} ${IMAGE_NAME} &>/dev/null
}

test_docker_run_usage() {
  info "Testing 'docker run' usage"
  docker run ${IMAGE_NAME} &>/dev/null
}

test_scl_usage() {
  local run_cmd="$1"
  local expected="$2"

  info "Testing the image SCL enable"
  out=$(docker run --rm ${IMAGE_NAME} /bin/bash -c "${run_cmd}")
  if ! echo "${out}" | grep -q "${expected}"; then
    echo "ERROR[/bin/bash -c "${run_cmd}"] Expected '${expected}', got '${out}'"
    return 1
  fi
  out=$(docker exec $(cat ${cid_file}) /bin/bash -c "${run_cmd}" 2>&1)
  if ! echo "${out}" | grep -q "${expected}"; then
    echo "ERROR[exec /bin/bash -c "${run_cmd}"] Expected '${expected}', got '${out}'"
    return 1
  fi
  out=$(docker exec $(cat ${cid_file}) /bin/sh -ic "${run_cmd}" 2>&1)
  if ! echo "${out}" | grep -q "${expected}"; then
    echo "ERROR[exec /bin/sh -ic "${run_cmd}"] Expected '${expected}', got '${out}'"
    return 1
  fi
}

# Perform GET request to the application container.
# First argument is request URI path.
# Second argument is expected HTTP response code.
# Third argument is PCRE regular expression that must match the response body.
test_response() {
  local uri_path="$1"
  local expected_code="$2"
  local body_regexp="$3"

  local url="http://$(container_ip):${test_port}${uri_path}"
  info "Testing the HTTP response for <${url}>"
  local max_attempts=10
  local sleep_time=1
  local attempt=1
  local result=1
  while [ $attempt -le $max_attempts ]; do
    response=$(curl -s -w '%{http_code}' "${url}")
    status=$?
    if [ $status -eq 0 ]; then
      response_code=$(printf '%s' "$response" | tail -c 3)
      response_body=$(printf '%s' "$response" | head -c -3)
      if [ "$response_code" -eq "$expected_code" ]; then
        result=0
      fi
      printf '%s' "$response_body" | grep -qP -e "$body_regexp" || result=1;
      break
    fi
    attempt=$(( $attempt + 1 ))
    sleep $sleep_time
  done
  return $result
}

# Match PCRE regular expression against container standard output.
# First argument is the PCRE regular expression.
# It expects standard output in ${tmp_dir}/out file.
test_stdout() {
  local regexp="$1"
  local output="${tmp_dir}/out"
  info "Testing the container standard output for /${regexp}/"
  grep -qP -e "$regexp" "$output";
}

# Match PCRE regular expression against container standard error output.
# First argument is the PCRE regular expression.
# It expects error output in ${tmp_dir}/err file.
test_stderr() {
  local regexp="$1"
  local output="${tmp_dir}/err"
  info "Testing the container error output for /${regexp}/"
  grep -qP -e "$regexp" "$output";
}

test_connection() {
    test_response '/' 200 ''
}

test_application() {
  # Verify that the HTTP connection can be established to test application container
  run_test_application &

  # Wait for the container to write it's CID file
  wait_for_cid

  test_scl_usage "perl --version" "v5.20.1"
  check_result $?

  test_connection
  check_result $?
  cleanup_test_app
}

# Build application, run it, perform test function, clean up.
# First argument is directory name.
# Second argument is function that expects running application. The function
# must return (or terminate with) non-zero value to report an failure,
# 0 otherwise.
# Other arguments are additional s2i options, like --env=FOO=bar.
# The test function have available container ID in $cid_file, container output
# in ${tmp_dir}/out, container stderr in ${tmp_dir}/err.
do_test() {
    test_name="$1"
    test_function="$2"
    shift 2

    # Old source-to-image 1.0.3 does not support multiple --env options.
    # TODO: Remove ARGUMENTS conversion after dropping support 1.0.3.
    local old_sti=0
    if [[ "$(LC_ALL=C s2i help build 2>&1)" =~ \
        'Specify an environment var NAME=VALUE,NAME2=VALUE2' ]]; then
        old_sti=1
    fi
    local argument arguments environment
    for argument in "$@"; do
        if [ "$old_sti" == '1' -a "${argument:0:6}" == '--env=' ]; then
            environment="${environment:+${environment},}${argument:6}"
        else
            arguments[${#arguments[*]}]="$argument"
        fi
    done
    if [ -n "$environment" ]; then
            arguments[${#arguments[*]}]="--env=${environment}"
    fi

    info "Starting tests for ${test_name}."

    tmp_dir=$(mktemp -d)
    check_result $?
    cid_file="${tmp_dir}/cid"
    s2i_args="--pull-policy=never"

    # Build and run the test application
    prepare
    run_s2i_build $s2i_args "${arguments[@]}"
    check_result $?
    run_test_application >"${tmp_dir}/out" 2>"${tmp_dir}/err" &
    wait_for_cid

    # Perform user-supplied test function
    $test_function;
    check_result $?

    # Terminate the test application and clean up
    cleanup_test_app
    cleanup
    rm -rf "$tmp_dir"
    info "All tests for the ${test_name} finished successfully."
}


# List of tests to execute:

# This is original test that does more things like s2i API checks. Other tests
# executed by do_test() will not repeat these checks.
test_1() {
    test_name='sample-test-app'
    info "Starting tests for ${test_name}"

    cid_file=$(mktemp -u --suffix=.cid)

    # Since we built the candidate image locally, we don't want S2I attempt to pull
    # it from Docker hub
    s2i_args="--pull-policy=never"

    prepare
    run_s2i_build $s2i_args
    check_result $?

    # Verify the 'usage' script is working properly when running the base image with 's2i usage ...'
    test_s2i_usage
    check_result $?

    # Verify the 'usage' script is working properly when running the base image with 'docker run ...'
    test_docker_run_usage
    check_result $?

    # Test application with default UID
    test_application

    # Test application with random UID
    CONTAINER_ARGS="-u 12345" test_application

    info "All tests for the ${test_name} finished successfully."
    cleanup
}
test_1

# Check scripts installed from CPAN are available to the application.
test_2_function() {
    test_response '/' 200 'Usage'
}
do_test 'binpath' 'test_2_function'

# Check a single PSGI application is recognized a mod_perl is autoconfigured.
test_3_function() {
    test_response '/' 200 '<title>Web::Paste::Simple'
}
do_test 'psgi' 'test_3_function'

# Check variables can select a PSGI application and set URI path.
test_4_function() {
    test_response '/path' 200 '<title>Web::Paste::Simple' && \
    test_response '/cpanfile' 200 'requires'
}
do_test 'psgi-variables' 'test_4_function' \
    '--env=PSGI_FILE=./application2.psgi' '--env=PSGI_URI_PATH=/path'

# Check httpd access_log flows to stdout, error_log to stdout.
# TODO: send error_log to stderr after dropping support for broken
# docker < 1.9.
test_5_function() {
    test_response '/' 200 'Text in HTTP body' && \
    test_stdout '"GET /[^"]*" 200 ' && \
    test_stdout 'Warning on stderr'
}
do_test 'warningonstderr' 'test_5_function'

echo "Testing npm availibility"
ct_npm_works
check_result $?

info "All tests finished successfully."
